package yuyicman.core.factory
{
	import flash.display.*;
	import flash.events.*;
	import flash.media.Sound;
	import yuyicman.debug.Debugger;
	
	
	[Event(name="event_asset_factory_ready", type="yuyicman.core.factory.AssetFactory")]
	
	final public class AssetFactory extends EventDispatcher
	{
		
		private var _loader:Loader = null;
		static public const EVENT_ASSET_FACTORY_READY:String = "event_asset_factory_ready";
		
		
		public function AssetFactory(target:IEventDispatcher=null)
		{
			super(target);
		}
		public function initialize( lib:Class ):void
		{
			_loader = new Loader;
			_loader.contentLoaderInfo.addEventListener(Event.INIT,_onLibraryReady);
			_loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR,_onIOError);
			
			try{
				_loader.loadBytes( new lib );
			}catch(e:Error){
				Debugger.log( e.getStackTrace );
			}
		}
		public function createObject(name:String):*
		{
			var obj:* = Class(this._loader.contentLoaderInfo.applicationDomain.getDefinition(name));
			return new obj;
		}
		public function createDisplayObject(name:String):DisplayObject
		{
			var obj:* = Class(this._loader.contentLoaderInfo.applicationDomain.getDefinition(name));
			return new obj as DisplayObject;
		}
		
		public function createSimpleButton(name:String):SimpleButton{
			var obj:* = Class(this._loader.contentLoaderInfo.applicationDomain.getDefinition(name));
			return new obj as SimpleButton;
		}
		public function createBitmapData(name:String):BitmapData
		{
			var obj:* = Class(this._loader.contentLoaderInfo.applicationDomain.getDefinition(name));
			return new obj(0,0) as BitmapData;
		}
		public function createDisplaySound(name:String):Sound
		{
			var obj:* = Class(this._loader.contentLoaderInfo.applicationDomain.getDefinition(name));
			return new obj as Sound;
		}
		private function _onLibraryReady( evt:Event ):void
		{
			this._loader.removeEventListener(Event.INIT,_onLibraryReady);
			this.dispatchEvent(new Event(EVENT_ASSET_FACTORY_READY));
		}
		private function _onIOError(evt:IOErrorEvent):void
		{
			Debugger.log( "AF IOError:"+evt.text );
		}
		
	}
}